<?php session_start();

	define("DB_SERVER", "localhost");
	define("DB_USER", "flatshare");
	define("DB_PASS", "flatPWD1");
	define("DB_NAME", "flatshare");
	
	$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
	mysql_select_db(DB_NAME, $connection) or die(mysql_error());
	
	
	// code to check user logins, make sure only authorized people are actually logged in for every page
	$username = $_POST['username'];
	$password = $_POST['password'];
	$task = $_POST['task'];
	
	$billDesc = $_POST['billDesc'];
	$billTotal = $_POST['billTotal'];
	$billDue = $_POST['billDue'];
	//$usernameArr = $_POST['usernamesArr'];
	//$shares = $_POST['shares'];
	
	if (!checkUserPass($username, $password)) {
		echo "correct username/password, ";
		if ($task == "getMembers") {
			// echo 'inside the task, ';
			$groupid = checkUserGroup($username);
			$members = getMembers($groupid);////
			$membercount = 0;
			
			echo 'group id = ' . ($groupid) . ', ';/////
			//echo 'members var = ' . $members . ', ';
			
			// loop to iterate through each row in the returned table
			while ($row = mysql_fetch_array($members)) {
				$membercount = $membercount + 1;
				echo '<' . $membercount . '>';
				echo '<username>' . $row[0] . '</username>';
				echo '<firstname>' . $row[1] . '</firstname>';
				echo '<lastname>' . $row[2] . '</lastname>';
				echo '</' . $membercount . '>';
			}
		}
		if ($task == "addNewBill"){
			$usernameArr = $_POST['usernamesArr'];
			$userArr = explode('##', $usernameArr);
			
			$shares = $_POST['shares'];
			$sharesArr = explode('##', $shares);
			
			// this should create the bill in the bill_info database
			$billid = createBill($username, $billDesc, "bill", $billTotal, $billDue);
			
			if ($billid > 0) {
				// here you put the code that iterates through each member and adds their share using
				// addShare function below
				
				for($i = 0; $i < 7; $i++){
					if($userArr[$i] != "" && $sharesArr[$i] != ""){
						addShare($billid, $userArr[$i], $sharesArr[$i]);
						}
				}
				echo "New Bill Added, ";
			}
		}
		if($task == "addNewChore"){
			$usernameArr = $_POST['usernamesArr'];
			$userArr = explode('##', $usernameArr);
			
			$shares = $_POST['shares'];
			$sharesArr = explode('##', $shares);
			
			// this should create the bill in the bill_info database
			$billid = createBill($username, $billDesc, "chore", 0, $billDue);
			
			if ($billid > 0) {
				// here you put the code that iterates through each member and adds their share using
				// addShare function below
				
				for($i = 0; $i < 7; $i++){
					if($userArr[$i] != ""){
						addChore($billid, $username);
						}
				}
				echo "New Chore Added, ";
			}
		}
		if($task == "getBillsAndChores"){
			$bills = getBills($username);
			$chores = getChores($username);
			echo "GET, ";
			
			$counter = 0;
			while ($bill = mysql_fetch_array($bills)){
				$counter++;
				
				echo '<bill' . $counter . '>';
				echo '<billid>' . $bill[0] . '</billid>';
				echo '<billname>' . $bill[1] . '</billname>';
				echo '<billshare>' . $bill[2] . '</billshare>';
				echo '<billdue>' . $bill[3] . '</billdue>';
				echo '<billpaid>' . $bill[4] . '</billpaid>';
				echo '<paycon>' . $bill[5] . '</paycon>';
				echo '</bill'. $counter . '>';
			}
			$counter = 0;
			while ($chore = mysql_fetch_array($chores)){
				$counter++;
				
				echo '<chore' . $counter . '>';
				echo '<billid>' . $chore[0] . '</billid>';
				echo '<billname>' . $chore[1] . '</billname>';
				echo '<billdue>' . $chore[2] . '</billdue>';
				echo '<chorecom>' . $chore[3] . '</chorecom>';
				echo '</chore' . $counter . '>';
			}
		}
		else {
			echo 'FAILED $TASK';
		}
	}
	else {
		echo 'FAILED USERNAME';
	}
	
	//echo 'This is outside the control statement';
	
	/*******************************************************************************
	*																			   *
	*	Contained below are all of the PHP functions required for various aspects  *
	*	of the Flatshare site.													   *
	*																			   *
	*******************************************************************************/
	
	// function to return table containing any bills for given username
	function getBills ($username) {
		global $connection;
		
		$q = "SELECT bill_info.Bill_ID, Bill_Name, Bill_Share, Bill_Due, Bill_Paid, Payment_Confirmed FROM bill_info, bill_users WHERE bill_users.Username='$username' AND bill_info.Bill_ID=bill_users.Bill_ID";
		
		return mysql_query($q, $connection);
	}
	
	// function to return table containing any chores for the given username
	function getChores ($username) {
		global $connection;
		
		$q = "SELECT bill_info.Bill_ID, Bill_Name, Bill_Due, Chore_Completed FROM bill_info, chore_users WHERE chore_users.Username='$username' AND bill_info.Bill_ID=chore_users.Bill_ID";
		
		return mysql_query($q, $connection);
	}


	// function to add a chore to the database
	function addChore ($billid, $username) {
		global $connection;
		
		$q = "INSERT INTO chore_users (Bill_ID, Username) VALUES ('$billid', '$username')";
		
		return mysql_query($q, $connection);
	}
	
	function addShare ($billid, $username, $billshare) {
		global $connection;
		
		$q = "INSERT INTO bill_users (Bill_ID, Username, Bill_Share) VALUES ('$billid', '$username', '$billshare')";
		return mysql_query($q, $connection);
	}
	
	// function to add a bill/chore to the database
	function createBill ($username, $billname, $billtype, $billtotal, $billdue) {
		global $connection;
		
		list($d, $m, $y) = explode('/', $billdue);
		$mk = mktime(0, 0, 0, $m, $d, $y);
		$billdue = strftime('%Y-%m-%d',$mk);
		
		$q = "INSERT INTO bill_info (Username, Bill_Name, Bill_Type, Bill_Total, Bill_Due) VALUES ('$username', '$billname', '$billtype', '$billtotal', '$billdue')";
		$result = mysql_query($q, $connection);
		
		if (!$result) {
			return 0;
		}
		
		$q = "SELECT MAX(Bill_ID) FROM bill_info";
		$result = mysql_query($q, $connection);
		$dbarray = mysql_fetch_array($result);
		
		return $dbarray[0];
	}
	
	// function to return array of username/firstname/lastname/email of all non-admin members of a group
	function getMembers ($groupid) {
		global $connection;

		$q = "SELECT group_members.Username, F_Name, L_Name, Email, Admin FROM users, group_members WHERE users.Username=group_members.Username AND group_members.Group_ID='$groupid'";
		
		return mysql_query($q, $connection);
	}
	
	// function checks if the username supplied is a member of a flatshare group
	function checkUserGroup($username) {
		global $connection;
		
		$q = "SELECT Group_ID FROM group_members WHERE username='$username'";
		$result = mysql_query($q, $connection);
		
		if (!$result || (mysql_numrows($result) < 1)) {
			return 0;
		}
		
		$dbarray = mysql_fetch_array($result);
		return $dbarray['Group_ID'];
	}
	
	// function to check whether the username/password are correct
	function checkUserPass($username, $password) {
		global $connection;
			  
		$username = str_replace("'","''",$username);
		$password = md5($password);
		
		// Verify that user is in database
		$q = "SELECT password FROM users WHERE username = '$username'";
		$result = mysql_query($q, $connection);
		if(!$result || (mysql_numrows($result) < 1)) {
			return 1; //Indicates username failure
		}      
		 
		// Retrieve password from result
		$dbarray = mysql_fetch_array($result);
		
		// Validate that password is correct
		if($password == $dbarray['password']) {
			return 0; //Success! Username and password confirmed
		}
		else {
			return 1; //Indicates password failure
		}
	}
?>
